<template>
  <div class="chat-container">
    <div class="chat-header">
      <h2>房间号: {{ roomId }}</h2>
    </div>

    <div class="chat-messages" ref="messagesContainer">
      <ChatMessage
        v-for="(message, index) in messages"
        :key="index"
        :message="message"
        :is-ai="message.sender === 'AI'"
      />
    </div>

    <div class="chat-input">
      <div class="action-buttons">
        <a-button
          type="primary"
          :disabled="gameStarted"
          @click="startGame"
        >
          开始
        </a-button>
        <a-button
          danger
          :disabled="gameEnded"
          @click="endGame"
        >
          结束
        </a-button>
      </div>

      <a-input
        v-model:value="inputMessage"
        placeholder="输入消息..."
        @pressEnter="sendMessage"
      />

      <a-button
        type="primary"
        @click="sendMessage"
      >
        发送
      </a-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue'
import { useRoute } from 'vue-router'
import api from '@/services/api'
import ChatMessage from '@/components/ChatMessage.vue'

const props = defineProps({
  roomId: {
    type: [String, Number],
    required: true
  }
})

const messages = ref([])
const inputMessage = ref('')
const gameStarted = ref(false)
const gameEnded = ref(false)
const messagesContainer = ref(null)

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim()) return

  // 处理"开始"命令
  if (inputMessage.value === '开始' && !gameStarted.value) {
    startGame()
    return
  }

  // 添加用户消息
  addMessage(inputMessage.value, 'user')

  // 发送到后端
  try {
    const response = await api.sendMessage(props.roomId, inputMessage.value)
    addMessage(response.data, 'AI')

    // 检查游戏是否结束
    if (response.data.includes('游戏已结束')) {
      gameEnded.value = true
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    addMessage('发送消息失败，请重试', 'AI')
  }

  inputMessage.value = ''
}

// 添加消息到聊天记录
const addMessage = (content, sender) => {
  messages.value.push({
    content,
    sender,
    timestamp: new Date().toLocaleTimeString()
  })

  // 滚动到底部
  nextTick(() => {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  })
}

// 开始游戏
const startGame = async () => {
  if (gameStarted.value) return

  gameStarted.value = true
  addMessage('游戏规则如下：当玩家说“开始”时，系统会生成一个与古代相关的谜面，谜底限定为人物、物品、典故或自然现象（如“青钢-宝剑”“橙红-凌霄” ）。\n' +
    '        谜面需引用古文/诗句中的字词（如“吾不如老圃”射“圃” ），或描述特征（如“伞型”射“香菇” 但不可直言谜底。玩家猜测后，根据谜底特性给出三类反馈：\n' +
    '        “相近”：类别/材质/功能接近（如猜“砚台”对谜底“墨锭” ）。\n' +
    '        “相远”：完全无关（如猜“兵器”对谜底“茶盏”）。\n' +
    '        “部分相关”：某特征吻合但其他不符（需说明具体关联，如“材质正确但功能不符”）。\n' +
    '        特殊机制：\n' +
    '        卦象提示：若玩家连续3次“相远”，可提供易经卦象辅助（如“见震卦，主东方木器” ）。\n' +
    '        两覆一射：允许追加第二个限定字（如探春覆“人”+“窗”射“鸡” ）。', 'AI')
}

// 结束游戏
const endGame = async () => {
  if (gameEnded.value) return

  addMessage('结束', 'user')
  try {
    const response = await api.sendMessage(props.roomId, '结束')
    addMessage(response.data, 'AI')
    gameEnded.value = true
  } catch (error) {
    console.error('结束游戏失败:', error)
    addMessage('结束游戏失败，请重试', 'AI')
  }
}

// 自动滚动到底部
watch(messages, () => {
  nextTick(() => {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  })
}, { deep: true })
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.chat-header {
  text-align: center;
  margin-bottom: 20px;
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background: white;
  border-radius: 8px;
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  gap: 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.chat-input {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.action-buttons {
  display: flex;
  gap: 12px;
}
</style>
